package org.example.xsda.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.xsda.common.PageResult;
import org.example.xsda.entity.Dept;
import org.example.xsda.exception.BusinessException;
import org.example.xsda.mapper.DeptMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 院系服务
 */
@Slf4j
@Service
public class DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private RedisService redisService;

    // 缓存key前缀
    private static final String CACHE_KEY_DEPT = "dept:";
    private static final String CACHE_KEY_DEPT_LIST = "dept:list";

    /**
     * 分页查询院系
     */
    public PageResult<Dept> page(Long current, Long size, String keyword) {
        Page<Dept> page = new Page<>(current, size);
        LambdaQueryWrapper<Dept> wrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like(Dept::getDeptName, keyword)
                    .or().like(Dept::getDeptCode, keyword));
        }
        wrapper.orderByAsc(Dept::getSort);
        
        Page<Dept> deptPage = deptMapper.selectPage(page, wrapper);
        return new PageResult<>(deptPage.getTotal(), deptPage.getRecords(), deptPage.getCurrent(), deptPage.getSize());
    }

    /**
     * 获取所有院系（树形结构用，带缓存）
     */
    @SuppressWarnings("unchecked")
    public List<Dept> list() {
        // 先从缓存中获取
        Object cached = redisService.get(CACHE_KEY_DEPT_LIST);
        if (cached != null) {
            log.debug("从缓存中获取院系列表");
            return (List<Dept>) cached;
        }
        
        // 缓存未命中，从数据库查询
        LambdaQueryWrapper<Dept> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Dept::getSort);
        List<Dept> list = deptMapper.selectList(wrapper);
        
        // 存入缓存（1小时，院系信息变化不频繁）
        redisService.set(CACHE_KEY_DEPT_LIST, list, 1, java.util.concurrent.TimeUnit.HOURS);
        log.debug("将院系列表存入缓存");
        
        return list;
    }

    /**
     * 根据ID获取院系（带缓存）
     */
    public Dept getById(Long id) {
        String cacheKey = CACHE_KEY_DEPT + id;
        
        // 先从缓存中获取
        Object cached = redisService.get(cacheKey);
        if (cached != null) {
            log.debug("从缓存中获取院系信息：id={}", id);
            return (Dept) cached;
        }
        
        // 缓存未命中，从数据库查询
        Dept dept = deptMapper.selectById(id);
        if (dept == null) {
            throw new BusinessException("院系不存在");
        }
        
        // 存入缓存（1小时）
        redisService.set(cacheKey, dept, 1, java.util.concurrent.TimeUnit.HOURS);
        log.debug("将院系信息存入缓存：id={}", id);
        
        return dept;
    }

    /**
     * 新增院系
     */
    public void add(Dept dept) {
        // 检查编码是否已存在
        LambdaQueryWrapper<Dept> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dept::getDeptCode, dept.getDeptCode());
        Long count = deptMapper.selectCount(wrapper);
        if (count > 0) {
            throw new BusinessException("院系编码已存在");
        }

        deptMapper.insert(dept);
        
        // 清除缓存
        redisService.delete(CACHE_KEY_DEPT_LIST);
        
        log.info("新增院系成功：{}", dept.getDeptName());
    }

    /**
     * 更新院系
     */
    public void update(Dept dept) {
        Dept existDept = deptMapper.selectById(dept.getId());
        if (existDept == null) {
            throw new BusinessException("院系不存在");
        }

        // 检查编码是否重复
        LambdaQueryWrapper<Dept> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dept::getDeptCode, dept.getDeptCode());
        wrapper.ne(Dept::getId, dept.getId());
        Long count = deptMapper.selectCount(wrapper);
        if (count > 0) {
            throw new BusinessException("院系编码已存在");
        }

        deptMapper.updateById(dept);
        
        // 清除缓存
        redisService.delete(CACHE_KEY_DEPT + dept.getId());
        redisService.delete(CACHE_KEY_DEPT_LIST);
        
        log.info("更新院系成功：{}", dept.getDeptName());
    }

    /**
     * 删除院系
     */
    public void delete(Long id) {
        Dept dept = deptMapper.selectById(id);
        if (dept == null) {
            throw new BusinessException("院系不存在");
        }

        // 检查是否有子院系
        LambdaQueryWrapper<Dept> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dept::getParentId, id);
        Long count = deptMapper.selectCount(wrapper);
        if (count > 0) {
            throw new BusinessException("该院系下有子院系，无法删除");
        }

        deptMapper.deleteById(id);
        
        // 清除缓存
        redisService.delete(CACHE_KEY_DEPT + id);
        redisService.delete(CACHE_KEY_DEPT_LIST);
        
        log.info("删除院系成功：{}", dept.getDeptName());
    }
}

